import subprocess
import time

import pandas as pd

from LogConfig import getLog
from 配置文件 import VIEWPORT, accounts

logger=getLog('UTIL')


def format_date(date_value):
    """将日期格式化为'年 月 日'格式"""
    if isinstance(date_value, str):
        date_value = pd.to_datetime(date_value)
    return date_value.strftime('%Y年%m月%d日')


def get_days_diff(date1, date2):
    """计算两个日期之间的天数差"""
    return abs((date1 - date2).days)


def log_with_company(公司代码, level, message):
    """带公司代码前缀的日志输出"""
    full_message = f"[{公司代码}] {message}"
    if level == "error":
        logger.error(full_message)
    elif level == "debug":
        logger.debug(full_message)
    elif level == "info":
        logger.info(full_message)

def 登录(page, 用户名):
    account_info = accounts[用户名]
    username = 用户名  # 直接使用传入的用户名
    password = account_info[0]  # 获取密码
    IF_SUPERVISOR = account_info[1]  # 获取主管权限
    logger.info(f"使用账号: {username}")

    try:
        # 添加重试机制和超时设置
        page.goto("http://cessf.chnenergy.com.cn:8070/sap(bD16aCZjPTgwMA==)/bc/bsp/sap/crm_ui_start/default.htm",
                  timeout=30000, wait_until="load")
    except Exception as e:
        logger.error(f"访问登录页面失败: {e}")
        return None

    # 获取账号密码
    if 用户名 in accounts:
        try:
            account_info = accounts[用户名]
            username = 用户名  # 直接使用传入的用户名
            password = account_info[0]  # 获取密码
            IF_SUPERVISOR = account_info[1]  # 获取主管权限
            logger.info(f"使用账号: {username}")

            if "id.ceic.com/auth/realms/" in page.url:  # 因为playwright能记住上下文，反正开浏览器的时候，有可能已经登录了，所以当页面url为这个的时候，才会登录
                # 如果已经登录了，就会直接很快跳到个人待办，而不需要输密码，从而找不到输入框报错
                page.fill("[name='username']", username)
                page.fill("[name='password']", password)
                page.click("#kc-submit")
                # 等待登录完成
                page.wait_for_load_state("networkidle", timeout=30000)

            if IF_SUPERVISOR == 1:
                page.click('//*[@id="ZAIC_AGENT_M"]')  # 主管登录

            return page
        except Exception as e:
            logger.error(f"登录过程中发生异常: {e}")
            return None
    else:
        logger.info(f"用户名 {用户名} 不存在，请检查配置")
        return None

def 初始化浏览器(p, 无头模式, 用户名=None):
    # # 清理可能存在的Chrome进程
    # try:
    #     subprocess.run(["taskkill", "/f", "/im", "chrome.exe"],
    #                    capture_output=True, check=False)
    #     time.sleep(1)  # 等待进程完全结束
    # except Exception as e:
    #     logger.warning(f"清理Chrome进程时出现异常: {e}")

    # 设置浏览器参数
    chrome_path = r"chrome-win64\chrome.exe"
    chromium_path = r"chromium-1181\chrome-win\chrome.exe"

    # 为每个账号创建独立的用户数据目录
    if 用户名:
        user_data_dir = f"./user_data_{用户名}"
    else:
        user_data_dir = "./user_data"

    # 优化浏览器启动参数 - 移除可能导致冲突的参数
    args_list = [
        "--disable-blink-features=AutomationControlled",
        "--disable-web-security",
        "--no-sandbox",
        "--disable-dev-shm-usage",
        "--disable-gpu",
        "--disable-gpu-sandbox",
        "--disable-software-rasterizer",
        "--disable-background-timer-throttling",
        "--disable-backgrounding-occluded-windows",
        "--disable-renderer-backgrounding",
        "--disable-features=TranslateUI",
        "--disable-ipc-flooding-protection",
        "--disable-background-networking",
        "--disable-sync",
        "--disable-default-apps",
        "--disable-extensions",
        "--disable-component-extensions-with-background-pages",
        "--disable-client-side-phishing-detection",
        "--disable-popup-blocking",
        "--disable-notifications",
        "--disable-infobars",
        "--disable-breakpad",
        "--disable-hang-monitor",
        "--disable-prompt-on-repost",
        "--disable-domain-reliability",
        "--disable-component-update",
        "--disable-background-mode",
        "--disable-plugins",
        "--disable-plugins-discovery",
        "--disable-preconnect",
        "--disable-translate",
        "--no-default-browser-check",
        "--no-pings",
        "--no-first-run",
        "--no-service-autorun",
        "--metrics-recording-only",
        "--mute-audio",
        "--enable-automation",
        "--remote-debugging-port=0",
        "--use-mock-keychain",
        "--force-color-profile=srgb",
        "--memory-pressure-off",
        "--max_old_space_size=4096"
    ]

    if not 无头模式:
        args_list.append('--start-maximized')

    # 尝试启动浏览器，增加重试机制
    max_retries = 3
    for attempt in range(max_retries):
        try:
            logger.info(f"尝试启动浏览器 (第{attempt + 1}次/共{max_retries}次)")

            if not 无头模式:
                browser = p.chromium.launch_persistent_context(
                    executable_path=chromium_path,
                    headless=无头模式,
                    args=args_list,
                    no_viewport=True,
                    user_data_dir=user_data_dir,
                    timeout=30000  # 30秒超时
                )
            else:
                browser = p.chromium.launch_persistent_context(
                    executable_path=chromium_path,
                    headless=无头模式,
                    args=args_list,
                    viewport=VIEWPORT,
                    user_data_dir=user_data_dir,
                    timeout=30000  # 30秒超时
                )

            logger.info("浏览器启动成功")
            break

        except Exception as e:
            logger.error(f"第{attempt + 1}次启动浏览器失败: {e}")

            if attempt < max_retries - 1:
                # 清理可能的残留进程
                try:
                    subprocess.run(["taskkill", "/f", "/im", "chrome.exe"],
                                   capture_output=True, check=False)
                    time.sleep(2)  # 等待更长时间
                except Exception:
                    pass
            else:
                # 最后一次尝试失败，抛出异常
                raise Exception(f"经过{max_retries}次尝试后仍无法启动浏览器: {e}")

    if len(browser.pages) == 0:
        page = browser.new_page()
    else:
        page = browser.pages[0]

    return browser, page